package com.taotao.search.controller;

import java.io.UnsupportedEncodingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.search.bean.SearchResult;
import com.taotao.search.service.SearchItemService;

@Controller
public class SearchController {

	@Autowired
	private SearchItemService searchItemService;
	
	private static final int DEFAULT_ROWS = 32;
	
	@RequestMapping(value = "search",method = RequestMethod.GET)
	public ModelAndView search(@RequestParam("q") String keyword,
			@RequestParam(value = "page", defaultValue = "1") Integer page) {
		ModelAndView modelAndView = new ModelAndView("search");
		
		try {
			keyword = new String(keyword.getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		modelAndView.addObject("query",keyword);//查询关键字
		
		SearchResult result;
		try {
			result = searchItemService.searchItems(keyword,page,DEFAULT_ROWS);
		} catch (Exception e) {
			e.printStackTrace();
			result  = new SearchResult(0L, null);
		}
		
		modelAndView.addObject("itemList", result.getList());//数据
		
		long pages = result.getTotal() % DEFAULT_ROWS == 0 ? result.getTotal()/DEFAULT_ROWS :result.getTotal()/DEFAULT_ROWS+1; 
		
		modelAndView.addObject("page", page);//页数
		modelAndView.addObject("pages", pages);//总页数
		return modelAndView;
	}
}
